package lookas.xml;

import java.io.File;
import java.io.InputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

public class XML{
    private static final Log log = LogFactory.getLog(XML.class);

    public static void save(Document xmldoc, String type, String dest)
        throws TransformerException{

        Transformer transformer = prepareTransform(type);
        if(transformer == null)
            transformer = TransformerFactory.newInstance().newTransformer();

        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(xmldoc), new StreamResult(new File(
            dest)));
        log.info("Zapisano do xml");
    }

    private static Transformer prepareTransform(String type)
        throws TransformerException{

        if(type == null)
            return null;
        InputStream resource = XML.class.getClass().getResourceAsStream(
            String.format("/xslt/%s.xsl", type));
        if(resource == null)
            return null;
        StreamSource source = new StreamSource(resource);
        log.info("Transformacja XSL");
        return TransformerFactory.newInstance().newTransformer(source);
    }
}
